package sgg.algorithm.datastructure.recursion;

/**
 * @author: Michael
 * @date: 2025/4/29
 * @desc: 八皇后问题
 */
public class Queen8 {

    int max = 8;

    // 0, 4, 7, 5, 2, 6, 1, 3
    int[] arr = new int[max];

    static int count = 0;

    public static void main(String[] args) {
        Queen8 queen8 = new Queen8();
        queen8.check(0);
        System.out.printf("一共有%d解法", count);
    }

    public void check(int n){
        if (n == max) {
            print();
            return;
        }

        for (int i = 0; i < max; i++) {
            arr[n] = i;
            if (judge(n)) {
                check(n + 1);
            }
        }
    }

    private boolean judge(int n) {
        for (int i = 0; i < n; i++) {
            if (arr[i] == arr[n] || Math.abs(arr[i] - arr[n]) == Math.abs(i - n)) {
                // 如果当前皇后，和之前的皇后在 同一列 或是 同一个斜线，返回false
                return false;
            }
        }
        return true;
    }

    private void print() {
        count++;
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

}
